<template>
  <div class="main">
    <div class="search">
      <div>
        <h2>排班模板</h2>
      </div>
      <div>
        <el-button @click="TemplateManagement">模板</el-button>

           
        <!-- <el-button type="primary" icon="el-icon-plus" @click="addtempleat">新增</el-button> -->
      </div>
    </div>
    <div>
      <el-calendar v-model="value">
        <template slot="dateCell" slot-scope="{data}">
          <template v-for="item in MonthDuty">
            <template v-if="item.day == data.day">
                <div :class="item.isHas?'dateCell active':'dateCell'" @click="adddate(data)">
                {{ data.day.split('-').slice(2).join('-') }}
              </div>
            </template>
           
          </template>
          
        </template>
      </el-calendar>
    </div>
    <!-- 模板管理 -->
    <el-dialog title="模板管理" :visible.sync="mbglVisible" width="800px">
      <el-table :data="mbgllist" border style="width: 100%">
        <el-table-column prop="name" label="模板名称" />
        <el-table-column prop="typeString" label="是否默认">
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope">
            <el-button @click="handleClick(scope.row)" type="text" size="small">字段管理</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog width="30%" title="新增模板" :visible.sync="innerVisible" append-to-body>
        <el-form ref="mbform" :model="mbform" :rules="rules" label-width="80px">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="mbform.name"></el-input>
          </el-form-item>
          <el-form-item label="是否默认" prop="type">
            <el-radio-group v-model="mbform.type">
              <el-radio :label="0">否</el-radio>
              <el-radio :label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSubmit">保存</el-button>
            <el-button @click="quxiao">取消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="xzmbbtn">新增模板</el-button>
      </div>
    </el-dialog>
    <!-- 排班内容 -->
    <el-dialog :title="mbtitle" :visible.sync="templatedialogVisible" width="500px">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="name" label="名称" width="180">
        </el-table-column>
        <el-table-column prop="sort" label="排序" width="180">
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="shanchu(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="tianjia">添加</el-button>
      </div>
      <div>
        <el-dialog width="30%" title="添加模板" :visible.sync="innerVisible2" append-to-body>
          <el-form :model="innerFrom">
            <el-form-item label="名称">
              <el-input v-model="innerFrom.name" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="排序">
              <el-input v-model="innerFrom.sort" autocomplete="off"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitFormAdd">保存</el-button>
          </div>
        </el-dialog>
      </div>
    </el-dialog>

    <el-dialog title="排班内容" :visible.sync="dialogFormVisible" width="700px">
      <div class="pbline">
        <p>日期：{{ form.day }}</p>
        <el-select v-model="templatechangeId" placeholder="请选择" @change="changetemp" >
          <el-option v-for="item in options" :key="item.value" :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>

      <el-table :data="form.array" style="width: 100%">
        <el-table-column prop="name" label="职位">
        </el-table-column>
        <el-table-column label="姓名">
          <template slot-scope="scope">
            <el-select disabled v-model="scope.row.xingming" placeholder="请选择">
              <el-option
                v-for="item in useroptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
            <!-- <el-input v-model="scope.row.xingming"></el-input> -->
          </template>
        </el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { queryPage, addUser, delUser } from "@/api/dutyUserApi";
import { queryTemplateOne,queryTemplateByDay,queryMonthDuty, addTemplateDetail, queryDetailByTemplateId, addDuty, queryDutyByDay, addTemplate, queryTemplateAll, deleteTemplate } from "@/api/date";
export default {
  name: "date",
  data() {
    return {
      value: new Date(),
      dialogFormVisible: false,
      templatedialogVisible: false,
      tableData: [],
      ruleForm: [
        {
          name: '',
          sort: '',
        }
      ],
      flag: true,
      form: {
        day: '',
        array: []
      },
      rules: {},
      innerFrom: {
        name: '',
        sort: '',
      },
      mbglVisible: false,
      mbgllist: [],
      innerVisible: false,
      innerVisible2: false,
      rules: {
        name: [
          { required: true, message: '请输入模板名称', trigger: 'blur' },
        ],
        type: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
      },
      mbform: {
        name: '',
        type: ''
      },
      mbtitle: '',
      templatechangeId: '',
      options: [],
      today: '',
      template:[],
      MonthDuty:[],
      useroptions:[],
      params: {
        name: '',
        total: 0,
        pageNum: 1,
        pageSize: 10000,
      },
    };
  },
  created() {
    this.getmbgllist()
    this.init()
    this.getuserlist()
  }, 
  
  methods: {
    getuserlist() {
      queryPage(this.params).then((res) => {
        if (res.code == 0) {
          this.useroptions = res.rows
        }
      });
    },
    handleSelected(date){
      this.MonthDuty.forEach(item=>{
        if(item.day == date){
          return item.isHas
        }
      })
    },
    init(){
      console.log(new Date());
      var now = new Date();
      var year = now.getFullYear(); //得到年份
      var month = now.getMonth(); //得到月份
      month = month + 1;
      month = month.toString().padStart(2, "0");
      var tomonth = year+'-'+month
      console.log(tomonth);
      queryMonthDuty({month:tomonth}).then(res => {
        this.MonthDuty = res.data
      
      })
    },
    searchdate(date){
 

      queryDutyByDay({day:date.day}).then(res => {
        this.form.array = res.data.map(item=>{
          item.name = item.key
          return item
        })
        res.data.forEach((item,index)=>{
          if(index == 0 ){
            this.templatechangeId= item.templateId
            return
          }

        })
      })
    },
    // 保存模板
    onSubmit() {
      this.$refs.mbform.validate((valid) => {
        if (valid) {
          addTemplate(this.mbform).then(res => {
            if (res.code == 0) {
              this.innerVisible = false
              this.$message.success('添加成功')
              this.mbform = {}
              this.getmbgllist()
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 新增模板
    xzmbbtn() {
      this.innerVisible = true
    },
    quxiao() {
      this.innerVisible = false
      this.mbform = {}
      this.$refs.mbform.clearValidate();
    },
    // 获取模板列表
    getmbgllist() {
      queryTemplateAll().then(res => {
        if (res.code == 0) {
          this.mbgllist = res.data.map(item => {
            item.typeString = item.type == 0 ? '否' : '是'
            return item
          })
          this.options = res.data.map(item => {
            if (item.type == 1) {
              this.templatechangeId = item.id
            }
            return { label: item.name, value: item.id }
          })

        }
      })
    },
    shanchu(row) {
      console.log(row);
      deleteTemplate([row.id]).then(res => {
        if (res.code == 0) {
          this.$message.success("删除成功")
          this.getlist(this.templateId)
        }
      })
    },
    submitFormAdd() {
      this.innerFrom.templateId = this.templateId
      addTemplateDetail(this.innerFrom).then(res => {
        if (res.code == 0) {
          this.innerVisible2 = false
          this.$message.success('添加成功')
          this.innerFrom = {}
          this.getlist(this.templateId)
        }
      })
    },
    handleClick(item) {
      this.mbtitle = item.name
      this.templatedialogVisible = true
      // 添加模板
      this.templateId = item.id
      this.getlist(item.id)
    },
    getlist(id) {
      queryDetailByTemplateId({ templateId: id }).then(res => {
        if (res.code == 0) {
          this.tableData = res.data
        }
      })
    },
    changetemp(val) {
      this.templatechangeId = val
      queryDetailByTemplateId({ templateId: val }).then(res => {
        if (res.code == 0) {
          console.log(res,'res');
          this.form.array = res.data

        }
      })
      // this.getdaydetails(this.today,val)
      // this.searchdate({day:this.today})
      // queryDutyByDay({day:this.today}).then(res => {
      //   console.log("🚀 ~ file: index.vue:323 ~ queryDutyByDay ~ res:", res)
      //   this.form.array = res.data.map(item=>{
      //     item.name = item.key
      //     return item
      //   })
      // })
    },
    adddate(data) {
      this.today = this.form.day = data.day
      this.searchdate(data)
      
      this.dialogFormVisible = true

    },
    // 获取当前日期的排班
    getdaydetails(day, id) {
      queryDetailByTemplateId({ templateId: id }).then(res => {
        if (res.code == 0) {
          this.form.day = day
          this.template = res.data
          // this.tableData = res.data
          console.log("🚀 ~ file: index.vue:326 ~ queryDetailByTemplateId ~ res.data:", res.data)
        }
      })
    },
    tianjia() {
      this.innerVisible2 = true
    },
    TemplateManagement() {
      // 模板管理
      this.mbglVisible = true
    },
    save() {
      let obj = {}
      obj.day = this.form.day
      obj.dutyList = []
      obj.templateId = this.templatechangeId
      this.form.array.map(item => {
        obj.dutyList.push({ id: item.id, name: item.xingming })
      })
      addDuty(obj).then(res => {
        if (res.code == 0) {
          this.dialogFormVisible = false
          this.$message.success('添加成功')
        }
      })
    }
  },
};
</script>
<style scoped>
@import "~@/assets/css/adminstyle.css";
</style>
<style>
.el-calendar-table .el-calendar-day{
  padding: 0;
}
</style>

